// 知识库相关接口
import request from './request'
import type {
  CreateKnowledgeRequest,
  GetKnowledgeListResponse,
  CreateKnowledgeResponse,
} from '@/types/index'

// 获取知识库列表
export const getKnowledgeListAPI = (userId: string): Promise<GetKnowledgeListResponse> => {
  console.log('userId:', userId)
  const url = `/kbs?X-user-Id=${userId}`
  return request.get(url, {
    headers: {
      'X-user-Id': userId
    }
  })
}

// 新建知识库
export const createKnowledgeAPI = (data: CreateKnowledgeRequest): Promise<CreateKnowledgeResponse> => {
  return request.post('/kbs', data)
}

// 编辑知识库
export const editKnowledgeAPI = (id: string, name: string, cover_url: string): Promise<void> => {
  return request.put(`/kbs/edit`, {
    id,
    name,
    cover_url
  })
}

// 删除知识库
export const deleteKnowledgeAPI = (id: string): Promise<void> => {
  return request.delete(`/kbs/${id}`)
}

// 构建向量数据库
// 构建向量数据库
export async function buildVectorDBAPI(userId: string, kbId: string) {
  const url = '/build-vector-db';
  // 强制转为字符串，防止调用方传入数字
  const body = JSON.stringify({ userId: String(userId), kbId: String(kbId) });
  try {
    const res = await fetch(url, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body
    });
    const data = await res.json();
    return data;
  } catch (e) {
    console.error('[buildVectorDBAPI] fetch error:', e);
    throw e;
  }
}


// RAG问答接口
export async function ragAnswerAPI(params: { userId: string, kbId: string, prompt: string, top_k?: number }) {
  const url = '/rag-answer';
  const body = JSON.stringify({
    userId: String(params.userId),
    kbId: String(params.kbId),
    prompt: params.prompt,
    top_k: params.top_k || 3
  });
  console.log('ragAnswerAPI body:', body);
  const res = await fetch(url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body
  });
  return await res.json();
} 